<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拓客管理系统 - 首页</title>
    <style>
        /* 首页专用样式 - 完全重置 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        html, body {
            height: 100%;
            width: 100%;
            margin: 0;
            padding: 0;
            overflow: hidden;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #1e40af 0%, #3b82f6 50%, #2563eb 100%);
            background-attachment: fixed;
        }
        
        .app-container {
            display: flex;
            height: 100vh;
            width: 100vw;
            position: fixed;
            top: 0;
            left: 0;
        }
        
        /* 左侧导航栏 */
        .sidebar {
            width: 280px;
            min-width: 280px;
            flex-shrink: 0;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(20px);
            border-right: 1px solid rgba(255, 255, 255, 0.2);
            display: flex;
            flex-direction: column;
            height: 100vh;
            overflow-y: auto;
        }
        
        .sidebar-header {
            padding: 30px 25px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .logo {
            color: white;
            font-size: 24px;
            font-weight: 800;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
            margin-bottom: 8px;
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        .logo-desc {
            color: rgba(255, 255, 255, 0.8);
            font-size: 13px;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
        }
        
        .sidebar-nav {
            flex: 1;
            padding: 20px 0;
        }
        
        .nav-section {
            margin-bottom: 30px;
        }
        
        .nav-section-title {
            color: rgba(255, 255, 255, 0.6);
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 1px;
            padding: 0 25px 15px;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
        }
        
        .nav-item {
            display: flex;
            align-items: center;
            padding: 12px 25px;
            color: rgba(255, 255, 255, 0.9);
            text-decoration: none;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            border: none;
            background: none;
            width: 100%;
            text-align: left;
            cursor: pointer;
            font-size: 14px;
            font-family: inherit;
        }
        
        .nav-item::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            width: 4px;
            background: white;
            transform: scaleY(0);
            transition: transform 0.3s ease;
        }
        
        .nav-item:hover {
            background: rgba(255, 255, 255, 0.1);
            color: white;
            text-shadow: 0 0 10px rgba(255, 255, 255, 0.3);
        }
        
        .nav-item:hover::before {
            transform: scaleY(1);
        }
        
        .nav-item.active {
            background: rgba(255, 255, 255, 0.15);
            color: white;
        }
        
        .nav-item.active::before {
            transform: scaleY(1);
        }
        
        .nav-icon {
            font-size: 18px;
            margin-right: 15px;
            width: 20px;
            text-align: center;
        }
        
        .sidebar-footer {
            padding: 20px 25px;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .user-info {
            display: flex;
            align-items: center;
            color: rgba(255, 255, 255, 0.9);
            font-size: 14px;
            margin-bottom: 15px;
        }
        
        .logout-btn {
            width: 100%;
            padding: 10px 15px;
            background: rgba(239, 68, 68, 0.1);
            border: 1px solid rgba(239, 68, 68, 0.3);
            border-radius: 8px;
            color: rgba(239, 68, 68, 0.9);
            font-size: 13px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }
        
        .logout-btn:hover {
            background: rgba(239, 68, 68, 0.2);
            border-color: rgba(239, 68, 68, 0.5);
            color: #ef4444;
            transform: translateY(-1px);
        }
        
        .user-avatar {
            width: 36px;
            height: 36px;
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 12px;
            font-weight: 600;
            color: #333;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }
        
        /* 右侧内容区域 */
        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            background: rgba(255, 255, 255, 0.05);
            backdrop-filter: blur(10px);
            height: 100vh;
            overflow: hidden;
        }
        
        .main-header {
            padding: 25px 35px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            background: rgba(255, 255, 255, 0.05);
        }
        
        .page-title {
            color: white;
            font-size: 28px;
            font-weight: 700;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
            margin-bottom: 8px;
        }
        
        .page-subtitle {
            color: rgba(255, 255, 255, 0.8);
            font-size: 16px;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
        }
        
        .main-body {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            height: calc(100vh - 120px); /* 减去头部高度 */
        }
        
        .content-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 30px;
            margin-bottom: 40px;
            max-width: 800px;
            margin-left: auto;
            margin-right: auto;
        }
        
        .feature-card {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(15px);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 20px;
            padding: 30px;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
        .feature-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.5), transparent);
            transform: translateX(-100%);
            transition: transform 0.6s ease;
        }
        
        .feature-card:hover {
            transform: translateY(-5px);
            background: rgba(255, 255, 255, 0.15);
            border-color: rgba(255, 255, 255, 0.3);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
        }
        
        .feature-card:hover::before {
            transform: translateX(100%);
        }
        
        .feature-icon {
            font-size: 36px;
            margin-bottom: 20px;
            display: block;
        }
        
        .feature-title {
            color: white;
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 15px;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
        }
        
        .feature-desc {
            color: rgba(255, 255, 255, 0.8);
            font-size: 14px;
            line-height: 1.6;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
        }
        
        .quick-actions {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }
        
        .action-btn {
            display: inline-flex;
            align-items: center;
            gap: 10px;
            padding: 15px 25px;
            background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
            color: #333;
            text-decoration: none;
            border-radius: 12px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        }
        
        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
        }
        
        /* 加载状态样式 */
        .loading-state {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 60px 20px;
            color: rgba(255, 255, 255, 0.8);
        }
        
        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-top: 3px solid white;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 20px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* 动态内容区域 */
        #app-content-container {
            min-height: calc(100vh - 160px);
            height: 100%;
            width: 100%;
            display: flex;
            flex-direction: column;
        }
        
        /* 返回首页按钮 */
        .home-btn {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 16px;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            border-radius: 8px;
            color: rgba(255, 255, 255, 0.9);
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .home-btn:hover {
            background: rgba(255, 255, 255, 0.2);
            border-color: rgba(255, 255, 255, 0.3);
            color: white;
            transform: translateY(-1px);
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .sidebar {
                width: 250px;
                min-width: 250px;
            }
            
            .main-header {
                padding: 20px 25px;
            }
            
            .page-title {
                font-size: 24px;
            }
            
            .main-body {
                padding: 25px;
            }
            
            .content-grid {
                grid-template-columns: 1fr;
                gap: 20px;
                max-width: 100%;
            }
        }
        
        @media (max-width: 480px) {
            .sidebar {
                width: 220px;
                min-width: 220px;
            }
            
            .feature-card {
                padding: 20px;
            }
            
            .quick-actions {
                flex-direction: column;
                gap: 15px;
            }
            
            .action-btn {
                justify-content: center;
            }
        }
    </style>
</head>
<body>
    <div class="app-container">
        <!-- 左侧导航栏 -->
        <aside class="sidebar">
            <div class="sidebar-header">
                <div class="logo">拓客管理系统</div>
                <div class="logo-desc">智能化销售工具平台</div>
            </div>
            
            <nav class="sidebar-nav">
                <div class="nav-section">
                    <div class="nav-section-title">核心功能</div>
                    <button class="nav-item active" onclick="loadPage('common-words', '常用词管理')" data-page="common-words">
                        <span class="nav-icon">📝</span>
                        常用词管理
                    </button>
                    <button class="nav-item" onclick="loadPage('conversation', '语境对话')" data-page="conversation">
                        <span class="nav-icon">💬</span>
                        语境对话
                    </button>
                </div>
                
                <div class="nav-section" id="auth-section">
                    <div class="nav-section-title">帐户管理</div>
                    <a href="templates/login.html" class="nav-item" id="login-nav">
                        <span class="nav-icon">🔑</span>
                        登录系统
                    </a>
                    <a href="templates/register.html" class="nav-item" id="register-nav">
                        <span class="nav-icon">📝</span>
                        注册账户
                    </a>
                </div>
            </nav>
            
            <div class="sidebar-footer">
                <div class="user-info">
                    <div class="user-avatar">演</div>
                    <div>
                        <div>演示用户</div>
                        <div style="font-size: 12px; color: rgba(255,255,255,0.6);">在线</div>
                    </div>
                </div>
                <button id="logout-btn" class="logout-btn" onclick="logout()" style="display: none;">
                    <span>🚪</span>
                    退出登录
                </button>
            </div>
        </aside>
        
        <!-- 右侧内容区域 -->
        <main class="main-content">
            <!-- 默认首页内容（未登录状态） -->
            <div id="home-content">
                <header class="main-header">
                    <h1 class="page-title">欢迎使用拓客管理系统</h1>
                    <p class="page-subtitle">基于 HTMX 构建的现代化销售管理平台</p>
                </header>
                
                <div class="main-body">
                    <div class="content-grid">
                        <div class="feature-card">
                            <span class="feature-icon">📝</span>
                            <h3 class="feature-title">常用词管理</h3>
                            <p class="feature-desc">智能管理销售话术，按分类组织常用的销售词汇，提高沟通效率。支持快速搜索、分类管理和一键复制功能。</p>
                        </div>
                        
                        <div class="feature-card">
                            <span class="feature-icon">💬</span>
                            <h3 class="feature-title">语境对话</h3>
                            <p class="feature-desc">基于人工智能的对话生成，输入客户的话后选择回复类型，系统自动生成合适的专业回复话术。</p>
                        </div>
                    </div>
                    
                    <div class="quick-actions">
                        <a href="templates/login.html" class="action-btn">
                            <span>🔑</span>
                            立即登录
                        </a>
                        <a href="templates/register.html" class="action-btn">
                            <span>📝</span>
                            注册账户
                        </a>
                    </div>
                </div>
            </div>
            
            <!-- 登录后的应用框架 -->
            <div id="app-frame" style="display: none;">
                <header class="main-header">
                    <div style="display: flex; align-items: center; justify-content: space-between;">
                        <div>
                            <h1 class="page-title" id="frame-title">常用词管理</h1>
                            <p class="page-subtitle">管理和使用您的销售话术库</p>
                        </div>
                        <div class="header-actions">
                            <button onclick="goHome()" class="home-btn" title="返回欢迎页">
                                <span>🏠</span>
                                欢迎页
                            </button>
                        </div>
                    </div>
                </header>
                
                <div class="main-body">
                    <div id="app-content-container">
                        <div class="loading-state">
                            <div class="loading-spinner"></div>
                            <p>正在加载内容...</p>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script>
        // 当前活跃页面
        let currentPage = 'home';
        
        // 页面配置映射
        const pageConfig = {
            'common-words': {
                title: '常用词管理',
                subtitle: '管理和使用您的销售话术库',
                file: window.location.protocol === 'file:' ? 'templates/common_words_premium.html' : './templates/common_words_premium.html',
                extract: 'content'
            },
            'conversation': {
                title: '语境对话',
                subtitle: '智能生成销售对话和回复话术',
                file: window.location.protocol === 'file:' ? 'templates/conversation_premium.html' : './templates/conversation_premium.html',
                extract: 'content'
            }
        };
        
        // 加载页面内容
        async function loadPage(pageKey, title) {
            if (currentPage === pageKey) return;
            
            try {
                console.log(`开始加载页面: ${pageKey}, 标题: ${title}`);
                
                // 更新导航状态
                updateNavigation(pageKey);
                
                // 显示应用框架，隐藏欢迎页
                document.getElementById('home-content').style.display = 'none';
                document.getElementById('app-frame').style.display = 'block';
                
                const config = pageConfig[pageKey];
                if (!config) {
                    throw new Error('未找到页面配置');
                }
                
                // 更新标题和副标题
                document.getElementById('frame-title').textContent = config.title;
                const subtitle = document.querySelector('#app-frame .page-subtitle');
                if (subtitle) {
                    subtitle.textContent = config.subtitle || '加载中...';
                }
                
                // 显示加载状态
                const container = document.getElementById('app-content-container');
                container.innerHTML = `
                    <div class="loading-state">
                        <div class="loading-spinner"></div>
                        <p>正在加载 ${config.title}...</p>
                    </div>
                `;
                
                console.log(`尝试获取页面内容: ${config.file}`);
                
                // 获取页面内容
                let html = '';
                
                // 根据协议类型选择不同的加载方式
                if (window.location.protocol === 'file:') {
                    // 在file://协议下使用XMLHttpRequest
                    try {
                        html = await new Promise((resolve, reject) => {
                            const xhr = new XMLHttpRequest();
                            xhr.open('GET', config.file, true);
                            xhr.onreadystatechange = function() {
                                if (xhr.readyState === 4) {
                                    if (xhr.status === 200 || xhr.status === 0) { // 在file://协议下，status可能是0
                                        resolve(xhr.responseText);
                                    } else {
                                        reject(new Error(`XHR 请求失败: ${xhr.status}`));
                                    }
                                }
                            };
                            xhr.onerror = function() {
                                reject(new Error('加载文件失败'));
                            };
                            xhr.send();
                        });
                        console.log(`XHR获取到HTML内容，长度: ${html.length}`);
                    } catch (err) {
                        console.error('XHR加载失败:', err);
                        throw new Error(`无法使用XHR加载文件: ${err.message}`);
                    }
                } else {
                    // 在http(s)://协议下使用fetch API
                    const response = await fetch(config.file, {
                        headers: {
                            'Cache-Control': 'no-cache',
                            'Pragma': 'no-cache'
                        }
                    });
                    
                    console.log(`请求状态: ${response.status} ${response.statusText}`);
                    
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                    }
                    
                    html = await response.text();
                    console.log(`Fetch获取到HTML内容，长度: ${html.length}`);
                }
                
                // 直接使用HTML内容
                container.innerHTML = html;
                
                // 执行页面中的脚本
                executePageScripts(container);
                
                currentPage = pageKey;
                
                showToast(`${config.title} 加载成功`);
                
            } catch (error) {
                console.error('加载页面失败:', error);
                
                // 显示错误信息
                document.getElementById('app-content-container').innerHTML = `
                    <div style="text-align: center; padding: 60px 20px; color: rgba(255,255,255,0.8);">
                        <h3 style="color: #ef4444; margin-bottom: 15px;">加载失败</h3>
                        <p>无法加载 ${title}，请稍后重试。</p>
                        <p style="font-size: 12px; margin-top: 10px; opacity: 0.7;">${error.message}</p>
                        <button onclick="loadPage('${pageKey}', '${title}')" 
                                style="margin-top: 20px; padding: 10px 20px; background: #3b82f6; color: white; border: none; border-radius: 8px; cursor: pointer;">
                            重新加载
                        </button>
                    </div>
                `;
                
                showToast(`加载 ${title} 失败`, 'error');
            }
        }
        
        // 更新导航状态
        function updateNavigation(activePageKey) {
            document.querySelectorAll('.nav-item[data-page]').forEach(item => {
                item.classList.remove('active');
            });
            
            const activeItem = document.querySelector(`[data-page="${activePageKey}"]`);
            if (activeItem) {
                activeItem.classList.add('active');
            }
        }
        
        // 执行页面脚本
        function executePageScripts(container) {
            // 查找并执行页面中的脚本
            const scripts = container.querySelectorAll('script');
            scripts.forEach(script => {
                try {
                    if (script.src) {
                        // 外部脚本
                        const newScript = document.createElement('script');
                        newScript.src = script.src;
                        document.head.appendChild(newScript);
                    } else {
                        // 内联脚本
                        eval(script.textContent);
                    }
                } catch (error) {
                    console.warn('执行页面脚本失败:', error);
                }
            });
        }
        
        // 返回欢迎页
        function goHome() {
            document.getElementById('app-frame').style.display = 'none';
            document.getElementById('home-content').style.display = 'block';
            
            // 清除导航活跃状态
            document.querySelectorAll('.nav-item').forEach(item => {
                item.classList.remove('active');
            });
            
            currentPage = 'home';
        }
        
        // 路由处理函数（兼容性）
        function navigateTo(page) {
            window.location.href = page;
        }
        
        // 退出登录功能
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                // 清除本地存储的用户信息
                localStorage.removeItem('token');
                localStorage.removeItem('user');
                
                // 显示退出成功提示
                showToast('退出登录成功', 'success');
                
                // 延迟跳转到登录页面
                setTimeout(() => {
                    window.location.href = 'templates/login.html';
                }, 1000);
            }
        }
        
        // Toast通知功能
        function showToast(message, type = 'success') {
            const toast = document.createElement('div');
            toast.textContent = message;
            toast.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: ${type === 'error' ? '#ef4444' : '#3b82f6'};
                color: white;
                padding: 12px 20px;
                border-radius: 12px;
                font-size: 14px;
                font-weight: 500;
                z-index: 10000;
                box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
                transform: translateX(100%);
                transition: transform 0.3s ease;
            `;
            
            document.body.appendChild(toast);
            
            setTimeout(() => {
                toast.style.transform = 'translateX(0)';
            }, 100);
            
            setTimeout(() => {
                toast.style.transform = 'translateX(100%)';
                setTimeout(() => {
                    if (document.body.contains(toast)) {
                        document.body.removeChild(toast);
                    }
                }, 300);
            }, 3000);
        }
        
        // 初始化页面
        document.addEventListener('DOMContentLoaded', function() {
            console.log('页面初始化中...');
            
            // 添加消息监听器，处理来自iframe的消息
            window.addEventListener('message', function(event) {
                if (event.data.type === 'INSERT_WORD') {
                    // 将词汇插入到当前活动的对话输入框中
                    const conversationInput = document.querySelector('#app-content-container #conversation-input');
                    if (conversationInput) {
                        const cursorPos = conversationInput.selectionStart;
                        const textBefore = conversationInput.value.substring(0, cursorPos);
                        const textAfter = conversationInput.value.substring(cursorPos);
                        conversationInput.value = textBefore + event.data.word + textAfter;
                        conversationInput.selectionStart = conversationInput.selectionEnd = cursorPos + event.data.word.length;
                        conversationInput.focus();
                        
                        // 显示提示
                        showToast('已插入词汇: ' + event.data.word);
                    } else {
                        // 如果没有找到对话输入框，复制到剪贴板
                        navigator.clipboard.writeText(event.data.word).then(() => {
                            showToast('已复制到剪贴板: ' + event.data.word);
                        }).catch(() => {
                            showToast('复制失败');
                        });
                    }
                }
            });
            
            // 检查是否已登录
            const token = localStorage.getItem('token');
            const user = localStorage.getItem('user');
            const logoutBtn = document.getElementById('logout-btn');
            const authSection = document.getElementById('auth-section');
            
            if (token && user) {
                console.log('检测到用户已登录');
                // 已登录状态
                if (logoutBtn) {
                    logoutBtn.style.display = 'flex';
                }
                
                // 隐藏认证相关导航
                if (authSection) {
                    authSection.style.display = 'none';
                }
                
                // 更新用户信息显示
                try {
                    const userData = JSON.parse(user);
                    const userAvatar = document.querySelector('.user-avatar');
                    const userInfo = document.querySelector('.user-info div:last-child div:first-child');
                    
                    if (userAvatar && userData.name) {
                        userAvatar.textContent = userData.name.charAt(0);
                    }
                    if (userInfo && userData.name) {
                        userInfo.textContent = userData.name;
                    }
                } catch (error) {
                    console.error('解析用户数据失败:', error);
                }
                
                // 自动加载常用词管理页面
                console.log('将自动加载常用词管理页面');
                setTimeout(() => {
                    try {
                        loadPage('common-words', '常用词管理');
                    } catch (error) {
                        console.error('自动加载页面失败:', error);
                        showToast('自动加载页面失败，请手动刷新页面', 'error');
                    }
                }, 500);
                
            } else {
                console.log('用户未登录');
                // 未登录状态
                if (logoutBtn) {
                    logoutBtn.style.display = 'none';
                }
                
                if (authSection) {
                    authSection.style.display = 'block';
                }
            }
            
            // 添加导航项目点击效果
            document.querySelectorAll('.nav-item').forEach(item => {
                item.addEventListener('mouseenter', function() {
                    if (!this.classList.contains('active')) {
                        this.style.transform = 'translateX(5px)';
                    }
                });
                
                item.addEventListener('mouseleave', function() {
                    if (!this.classList.contains('active')) {
                        this.style.transform = 'translateX(0)';
                    }
                });
            });
            
            // 添加功能卡片动画
            document.querySelectorAll('.feature-card').forEach(card => {
                card.addEventListener('mouseenter', function() {
                    this.style.transform = 'translateY(-8px) scale(1.02)';
                });
                
                card.addEventListener('mouseleave', function() {
                    this.style.transform = 'translateY(0) scale(1)';
                });
            });
            
            showToast('拓客管理系统已就绪！');
        });
    </script>
</body>
</html>